#include "pg_opengl.hpp"
#include "ui_pg_opengl.h"

PgOpenGL::PgOpenGL(QWidget* parent)
    :PgBase(parent, "home")
    , ui(new Ui::PgOpenGL)
{
    ui->setupUi(this);
    QSurfaceFormat format;
    format.setSamples(16);
    
    gl_drawer = new GLDrawer(this,QString("cloud"),QString("cloud"));
    gl_drawer->setFormat(format);
    //gl_drawer->resize(640, 480);
    gl_drawer->set_point_size(3);
    ui->layout_gl->addWidget(gl_drawer);
    gl_drawer->show();

    QObject::connect(this,&PgOpenGL::sig_read_cloud_end,this,&PgOpenGL::slot_read_cloud_end);
}

PgOpenGL::~PgOpenGL()
{
    delete ui;
}

void PgOpenGL::slot_read_cloud_end(bool res)
{
    emit sigReqLoadingEnd();
    if(!res){
        qt::msg::warn("cloud read failed");
        return;
    }
    logger->info("gl data size {} {} {}", cloud.point_avg.x, cloud.point_avg.y, cloud.point_avg.z);
    std::shared_ptr<GLData> data_box = std::make_shared<GLData>("box_avg", GLData::Sort::BOX);
    gl::box2_data(cloud.point_min, pt::get_dimen(cloud.point_min, cloud.point_max), *data_box);

    gl_drawer->clear_data();
    //gl_drawer->add_data(data_box);
    gl_drawer->add_data(data_cloud);
    gl_drawer->normalize();
    //gl_drawer->start_timer();
    gl_drawer->update();
}

void PgOpenGL::on_btn_testLoading_clicked()
{
    emit sigReqLoading("home page loading");
}

void PgOpenGL::thd_read_cloud(const std::string path)
{
    file::read_cloud(path, cloud);
    if (cloud.size() < 1) {
        emit sig_read_cloud_end(false);
        return;
    }
    logger->info("cloud {} size {}", path, cloud.size());
    data_cloud = std::make_shared<GLData>(path, GLData::Sort::CLOUD);
    gl::cloud2_data(cloud, *data_cloud);
    emit sig_read_cloud_end(true);
}

void PgOpenGL::on_btn_selectFile_clicked()
{
    // select cloud file
    std::string path;
    QString file_path = QFileDialog::getOpenFileName(this, "选择文件", ".", "*.txt");
    if (file_path.isEmpty()) {
        qt::msg::warn("select file path is empty");
        return;
    }
    path = file_path.toStdString();
    ui->lab_fileName->setText(file_path);
    //read cloud in thread
    std::thread thd_read = std::thread(&PgOpenGL::thd_read_cloud,this,path);
    thd_read.detach();
    //loading
    emit sigReqLoading("wait read cloud file");
}